import requests
from flask import current_app

from extensions import db
from task_app.models import JobPlan,JobEvent


def api_scheduler_handler(plan: JobPlan):
    """任务函数：调度JobPlan计划中的API"""

    from app import app  # 重点，在函数内引入
    with app.app_context():  # 激活应用上下文，否则报错 RuntimeError: No application found, Either work inside a view function or push an application context
        if plan:
            task_id = plan.task_id
            method = plan.method
            url = plan.url
            params = plan.params
            # 调度API
            resp = requests.get(url, params=params) if method == "GET" else requests.post(url, data=params)
            current_app.logger.info("执行调度任务:%s" % task_id)
            current_app.logger.info("请求API方法:%s" % method)
            current_app.logger.info("请求API地址:%s" % url)
            current_app.logger.info("请求API结构:%s" % resp.text)
            # 添加定时事件记录
            record = JobEvent(
                task_id=plan.task_id,
                method=plan.method,
                url=plan.url,
                params=plan.params,
                result=resp.text
            )
            db.session.add(record)
            db.session.commit()


